class UserController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    /* already done in SecurityFilters.groovy
    def beforeInterceptor = [action:this.&auth,except:['login','loginOk','logout']]
    // defined as a regular method so its private
    def auth() {
        if(!session.user) {
            redirect(action:'login')
            return false
        }
    }
    */

    def avatar_image = {
        def u = User.get(params.id)
        response.contentType = u?.avatarType
        response.contentLength = u?.avatar.length
        response.outputStream.write(u?.avatar)
    }
    
    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ userInstanceList: User.list( params ), userInstanceTotal: User.count() ]
    }

    def show = {
        def userInstance = User.get( params.id )

        if(!userInstance) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ userInstance : userInstance ] }
    }

    def delete = {
        def userInstance = User.get( params.id )
        if(userInstance) {
            try {
                userInstance.delete(flush:true)
                flash.message = "User ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "User ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def userInstance = User.get( params.id )

        if(!userInstance) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ userInstance : userInstance ]
        }
    }

    def update = {
        System.out.println "Parms: " + params
        def userInstance = User.get( params.id )
        System.out.println "userInstance: " + params
        if(userInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(userInstance.version > version) {
                    
                    userInstance.errors.rejectValue("version", "user.optimistic.locking.failure", "Another user has updated this User while you were editing.")
                    render(view:'edit',model:[userInstance:userInstance])
                    return
                }
            }
            userInstance.properties = params

            def f = request.getFile('avatar')
            userInstance.avatar = f.getBytes()
            userInstance.avatarType = f.getContentType()

            if(!userInstance.hasErrors() && userInstance.save()) {
                flash.message = "User ${params.id} updated"
                redirect(action:show,id:userInstance.id)
            }
            else {
                render(view:'edit',model:[userInstance:userInstance])
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def userInstance = new User()
        userInstance.properties = params
        return ['userInstance':userInstance]
    }

    def save = {
        def userInstance = new User(params)

        // Get the avatar file from the multi-part request
        def f = request.getFile('avatar')
        userInstance.avatar = f.getBytes()
        userInstance.avatarType = f.getContentType()

        if(!userInstance.hasErrors() && userInstance.save()) {
            flash.message = "User ${userInstance.id} created"
            redirect(uri:"/user/login")
        }
        else {
            render(view:'create',model:[userInstance:userInstance])
        }
    }

    def login = {
        println params
        
        if (params != null && params.size() > 0 && params.userName != null) {

            println "here1" + params
            def userInstance = User.findByUserName( params.userName )

            println userInstance

            if (userInstance != null ) {
                if (userInstance.passWord == params.passWord ) {
                    flash.message = "User ${userInstance.userName} logged in."
                    session.user = userInstance
                    println "logged in"
                    redirect(controller:'callDetail', action:'list')
                } else {
                    flash.message = "Invalid password specified for user ${userInstance.userName}."
                    redirect(action:login)
                }
            } else {
                flash.message = "User ${params.userName} does not exist."
                redirect(action:login)
            }
        }
    }

    def logout = {
        session.invalidate();
        redirect(action:"login")
    }
}
